#include "login.h"
#include "umsdatabase.h"
#include <QtGui>
Login::Login():QDialog()
{
	setupUi(this);
	
	dbase = new UMSDatabase();
	editUser->setText(QSettings().value("username","").toString());	
	editPasswd->setText(QSettings().value("password","").toString());
	if(QSettings().value("work_auto",0).toInt()>0)
		cboxAuto->setCheckState(Qt::Checked);
	else
		cboxAuto->setCheckState(Qt::Unchecked);
	loadComboBox(cboxServer);
	if(!editPasswd->text().isEmpty()) checkSave->setCheckState(Qt::Checked);
}

void Login::loadComboBox(QComboBox *cbox)
{
	cbox->clear();	
	QSettings sets;
	int count = sets.beginReadArray(cbox->objectName());
	for(int i=0;i<count;i++){
		sets.setArrayIndex(i);
		cbox->addItem(sets.value("value","").toString());
	}
	sets.endArray();
	cbox->setCurrentIndex(0);
}

void Login::saveComboBox(QComboBox *cbox)
{
	QStringList slist;
	slist<<cbox->currentText();
	for(int i=0;i<cbox->count();i++){
		if(slist.indexOf(cbox->itemText(i))<0) slist << cbox->itemText(i);
		if(slist.count()>4) break;
	}	
	
	QSettings sets;
	sets.beginWriteArray(cbox->objectName());	
	int i = 0;
	foreach(QString s,slist){
		sets.setArrayIndex(i++);
		sets.setValue("value",s);
	}
	sets.endArray();
}


void Login::accept()
{
	
	dbase->setHost(cboxServer->currentText());
	QSettings().setValue("username",editUser->text());
	saveComboBox(cboxServer);
	
	if(checkSave->checkState()==Qt::Checked)
		QSettings().setValue("password",editPasswd->text());
	else
		QSettings().setValue("password","");
	QSettings().setValue("work_auto",cboxAuto->checkState());
	if(cboxAuto->checkState()==Qt::Unchecked && !dbase->open(editUser->text(),editPasswd->text())){
		QMessageBox::warning(this,trUtf8("Ошибка входа"),dbase->lastError());
		return;
	}
	
	QDialog::accept();
}
